import markdown


class MarkdownHandler:
    """Markdown处理类，封装文件打开和渲染功能"""

    def __init__(self):
        self.current_file = None
        self.markdown_text = ""

    def open_file(self, file_path):
        """打开并读取Markdown文件"""
        if not file_path:
            return False, "文件路径为空"

        try:
            with open(file_path, 'r', encoding='utf-8') as file:
                self.markdown_text = file.read()
                self.current_file = file_path
            return True, "文件读取成功"
        except Exception as e:
            return False, f"读取文件失败: {str(e)}"

    def get_markdown_text(self):
        """获取当前Markdown文本"""
        return self.markdown_text

    def convert_to_html(self, markdown_text=None):
        """将Markdown文本转换为HTML
        :param markdown_text: 可选的Markdown文本，如果不提供则使用self.markdown_text
        """
        text_to_convert = markdown_text if markdown_text is not None else self.markdown_text

        if not text_to_convert:
            return ""

        # 直接使用markdown库将Markdown转换为HTML
        html = markdown.markdown(
            text_to_convert,
            extensions=['markdown.extensions.fenced_code',
                        'markdown.extensions.tables',
                        'markdown.extensions.sane_lists']
        )

        # 创建完整的HTML文档，包含MathJax支持
        full_html = f"""
    <!DOCTYPE html>
    <html>
    <head>
        <meta charset="utf-8">
        <script src="https://cdn.tailwindcss.com"></script>
        <link href="https://cdn.jsdelivr.net/npm/font-awesome@4.7.0/css/font-awesome.min.css" rel="stylesheet">
        <script src="https://cdn.jsdelivr.net/npm/mathjax@3/es5/tex-mml-chtml.js"></script>
        <script>
            MathJax = {{
                tex: {{
                    inlineMath: [['$', '$'], ['\\(', '\\)']],  // 启用单美元符号
                    displayMath: [['$$', '$$'], ['\\[', '\\]']],
                    processEscapes: true,    // 允许使用 \$ 转义美元符号
                    packages: {{'[+]': ['ams']}}  // 加载额外的AMS符号支持
                }},
                options: {{
                    skipHtmlTags: ['script', 'noscript', 'style', 'textarea', 'pre', 'code'],
                    ignoreHtmlClass: 'tex2jax_ignore',
                    processHtmlClass: 'tex2jax_process'
                }},
                loader: {{
                    load: ['[tex]/ams']
                }},
                svg: {{
                    fontCache: 'global'
                }}
            }};
        </script>
    </head>
    <body class="bg-gray-50 min-h-screen">
        <div class="markdown-render">
            {html}
        </div>
    </body>
    </html>
    """
        return full_html